package tcpserver;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class RFIDConnection {

    private final String identity;

	private final AsynchronousSocketChannel channel;

	private final ByteBuffer buffer;

    private final ConcurrentSkipListSet<byte[]> receivedFrames = new ConcurrentSkipListSet<>();

	public RFIDConnection(String identity, AsynchronousSocketChannel channel, int bufferSize) {

		this.identity = identity;

		this.channel = channel;
		
		this.buffer = ByteBuffer.allocate(bufferSize);
	}

	public void flush() {

        byte[] lastFrame = new byte[buffer.limit() - buffer.position()];

        buffer.get(lastFrame).clear();

        receivedFrames.add(lastFrame);
	}

	public void asyncRead(CompletionHandler<Integer, RFIDConnection> callback) {

	    channel.read(buffer, this, callback);
    }

	public void asyncWrite(byte[] frame, CompletionHandler<Integer, RFIDConnection> callback) {

        receivedFrames.clear();

        channel.write(ByteBuffer.wrap(frame), this, callback);
    }

    public Set<byte[]> getCurrectRecivedFrames() {

        HashSet<byte[]> currentReceivedFrames = new HashSet<>();

        for(byte[] frame : receivedFrames) currentReceivedFrames.add(frame);

        return currentReceivedFrames;
    }

	public String getIdentity() {

	    return identity;
    }
}